package com.zmn.mcc.business.impl.dpermit.newchannel;

import com.zmn.base.common.data.common.dro.channel.ChannelDRO;
import com.zmn.base.common.data.common.query.channel.ChannelQuery;
import com.zmn.base.common.data.dubbo.interfaces.channel.ChannelListRemoteService;
import com.zmn.base.plat.engine.common.constant.DubboConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.manager.common.database.annotation.ReadOnlyConnection;
import com.zmn.mcc.business.interfaces.dpermit.newchannel.DpermitNewChannelBService;
import com.zmn.mcc.common.constant.DpermitConsts;
import com.zmn.mcc.manager.utils.DpermitUtil;
import com.zmn.mcc.model.dto.dpermit.DpermitBaseDO;
import com.zmn.mcc.model.dto.dpermit.DpermitSimpleDO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.assertj.core.util.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author heguanghua
 * @since 2020/06/11 12:42
 */
@Service
public class DpermitNewChannelBServiceImpl implements DpermitNewChannelBService {
    protected Logger logger = LoggerFactory.getLogger(DpermitNewChannelBServiceImpl.class);
    /**
     * 学才那边的渠道
     */
    @DubboReference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private ChannelListRemoteService channelListRemoteService;


    @Override
    @ReadOnlyConnection
    public List<DpermitSimpleDO> listNewChannelDpermitChecked(Integer status, List<? extends DpermitBaseDO> dpermitIds) {

        List<DpermitSimpleDO> items = new ArrayList<>();

        // 一级、二级、三级渠道列表
        ChannelQuery query = new ChannelQuery();
        query.setStatus(GlobalConsts.YES);
        ResponseDTO<List<ChannelDRO>> dto = channelListRemoteService.listByQuery(query);
        if (!dto.isSuccess() || CollectionUtil.isNullOrEmpty(dto.getData())) {
            return Lists.emptyList();
        }
        List<ChannelDRO> channelDROList = dto.getData();

        List<Integer> dpermitIdList = dpermitIds.stream().map(DpermitBaseDO::getDataId).collect(Collectors.toList());

        for (ChannelDRO channelDRO : channelDROList) {

            // 防止数据错误抛出异常
            if (channelDRO.getRank() == null) {
                continue;
            }

            DpermitSimpleDO simple = this.parseToDpermitSimpleDO(channelDRO);

            // 选中已分配
            if (CollectionUtil.isNotNullOrEmpty(dpermitIds) && dpermitIdList.contains(simple.getDataId())) {
                simple.setChecked(true);
            }

            items.add(simple);
        }
        return items;
    }

    @Override
    public List<DpermitSimpleDO> listNewChannelTreeAndDpermitChecked(Integer status, List<Integer> dpermitIds) {

        List<DpermitSimpleDO> items = new ArrayList<>();

        // 组织ID和简单组织对象的映射关系
        Map<Integer, DpermitSimpleDO> map = new HashMap<>(16);

        // 一二三级渠道
        ChannelQuery query = new ChannelQuery();
        query.setStatus(GlobalConsts.YES);
        ResponseDTO<List<ChannelDRO>> dto = channelListRemoteService.listByQuery(query);
        if (!dto.isSuccess() || CollectionUtils.isEmpty(dto.getData())) {
            return Lists.emptyList();
        }
        List<ChannelDRO> channelDROList = dto.getData();

        for (ChannelDRO channelDRO : channelDROList) {

            // 防止数据错误抛出异常
            if (channelDRO.getRank() == null) {
                continue;
            }

            // 简单组织对象
            DpermitSimpleDO simple = this.parseToDpermitSimpleDO(channelDRO);
            map.put(simple.getDataId(), simple);

            // 选中已分配
            if (CollectionUtil.isNotNullOrEmpty(dpermitIds) && dpermitIds.contains(simple.getDataId())) {
                simple.setChecked(true);
            }

            // 一级、二级、三级加入主列表
            if (channelDRO.getRank() == DpermitConsts.CHANNEL_LEVEL_ONE) {
                items.add(simple);
            } else if (channelDRO.getRank() > DpermitConsts.CHANNEL_LEVEL_ONE) {

                DpermitSimpleDO parent = map.get(simple.getParentId());
                if (parent != null) {
                    parent.getSubors().add(simple);
                }
            }
        }

        /**
         * 检查并处理简单数据对象选中状态
         * 下级部分选中则上级选中，下级全部选中则对上级标识
         */
        DpermitUtil.checkSelected(items, false);

        //业务需要展示全部子节点
        dealChildren(items);
        return items;
    }


    /**
     * 处理合作下子节点
     *
     * @param items
     */
    private void dealChildren(List<DpermitSimpleDO> items) {
        if (CollectionUtils.isNotEmpty(items)) {
            for (DpermitSimpleDO item : items) {
                if (item.getLevel() <= DpermitConsts.CHANNEL_LEVEL_TWO && CollectionUtils.isNotEmpty(item.getSubors()) && item.getSubors().stream().anyMatch(DpermitSimpleDO::isChecked)) {
                    item.setSubAll(false);
                } else {
                    item.setSubAll(true);
                }
                if (CollectionUtils.isNotEmpty(item.getSubors())) {
                    dealChildren(item.getSubors());
                }
            }
        }
    }

    /**
     * 转换为简单数据权限对象
     *
     * @param channelDRO
     * @return
     */
    private DpermitSimpleDO parseToDpermitSimpleDO(ChannelDRO channelDRO) {
        if (channelDRO == null) {
            return null;
        }
        DpermitSimpleDO simple = new DpermitSimpleDO();
        simple.setDataId(channelDRO.getChannelId());
        simple.setDataName(channelDRO.getName());
        simple.setParentId(channelDRO.getParentId());
        simple.setStatus(channelDRO.getStatus());
        simple.setLevel(channelDRO.getRank());
        return simple;
    }
}
